//
//  HttpUtil.m
//  GasEasyPay
//
//  Created by 张宁宁 on 16/11/23.
//  Copyright © 2016年 lirenkj. All rights reserved.
//

#import "HttpUtil.h"
#import "AFNetworking.h"
#import "JsonUtil.h"
#import "LocalStorage.h"
#import "ErrorForServer.h"
#import "Code.h"
#import "Result.h"
#import "LoginViewController.h"

@implementation HttpUtil
SYNTHESIZE_SINGLETON_FOR_CLASS(HttpUtil);



-(NSString*)getLocalHost{
    LocalStorage * ls = [[LocalStorage alloc]init];
    return [ls getHttpConfig];;
}

/**
 *  判断网络状态
 */

- (void) netWorkReachability:(void (^)(NetWorkState status))netWorkStatus
{
    
    __block NetWorkState state;
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
                DDLogError(@"2G,3G,4G...的网络");
                state = WWAN;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                DDLogError(@"wifi的网络");
                state = WIFI;
                netWorkStatus(state);
                break;
            case AFNetworkReachabilityStatusUnknown:
                DDLogError(@"未识别的网络");
            case AFNetworkReachabilityStatusNotReachable:
                DDLogError(@"不可达的网络(未连接)");
            default:
                DDLogError(@"其他");
                state = NONET;
                netWorkStatus(state);
                break;
        }
        [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

/**
 *  网络请求的方法
 *
 *  @param methords   请求方法 GET POST PUT DELETE
 *  @param url        网络请求url
 *  @param parameters 请求参数
 *  @param isjsondic  请求参数是否是Json格式
 *  @param success    success 回调
 *  @param failure    failure 回调
 */

-(void)doRequest:(HttpMethods)methords urlString:(NSString*)url parameters:(id)parameters isJsonDic:(BOOL)isjsondic success:(void (^)( id json ))success
         failure:(void (^)( NSString *msg))failure{
    NSString * httpUrl =[NSString stringWithFormat:@"%@%@",[self getLocalHost],url];
    DDLogError(@"请求的Url:====>%@\n",httpUrl);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    if (isjsondic) {
        [manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
        
        DDLogError(@"请求的参数Json:====>\n%@",[JsonUtil toJSONData:parameters]);
    }else{
        DDLogError(@"请求的参数键值对:====>\n");
        for (NSString* key in [(NSDictionary*)parameters allKeys]) {
            DDLogError(@"%@=%@\n",key,[(NSDictionary*)parameters objectForKey:key]);
        }
    }
    
    switch (methords) {
        case GET:{
            DDLogError(@"请求的方式:GET\n");
            [manager GET:httpUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                [self checkError:success failure:failure Response:responseObject];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self fail:failure ResponceType:Timeout Response:error];
            }];
        }
            break;
        case PUT:{
            DDLogError(@"请求的方式:PUT\n");
            [manager PUT:httpUrl parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
                
                
                [self checkError:success failure:failure Response:responseObject];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                
                [self fail:failure ResponceType:Timeout Response:error];
            }];
        }
            break;
        case POST:{
            DDLogError(@"请求的方式:POST\n");
            [manager POST:httpUrl parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                [self checkError:success failure:failure Response:responseObject];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [self fail:failure ResponceType:Timeout Response:error];
                
            }];
        }
            break;
        case DELETE:{
            DDLogError(@"请求的方式:DELETE\n");
            [manager DELETE:httpUrl parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                [self checkError:success failure:failure Response:responseObject];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [self fail:failure ResponceType:Timeout Response:error];
                
            }];
        }
            break;
        default:
            break;
    }
}
/**
 *  检查错误类型(现在已经过滤的errorcode 和  result 的失败  成功 自己进行处理)
 *
 *  @param success  请求成功
 *  @param failure  请求失败
 *  @param response 请求的反馈
 */

- (void)checkError:(void (^)(NSDictionary * json ))success
           failure:(void (^)(NSString *msg))failure Response:(id)response{
    NSDictionary *dic = response;
    DDLogError(@"返回的JSON数据===>\n%@", [JsonUtil toJSONData:response]);
    Code *code = [Code mj_objectWithKeyValues:dic];
    if (![code isOK]) {
        
        if ([code.code isEqualToString:@"20000"]) {
            //token验证失败（非本人修改密码导致）
            [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"token"];
            [LocalStorage deleteAvatarImage:@"userInfoPicture.png"];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:[[LoginViewController alloc]init]];
            [nav setNavigationBarHidden:YES animated:NO];
            [UIView restoreRootViewController:nav];
            [DialogUtil showSuccess:@"登录过期，请重新登录"];
            
        }else{
            [self fail:failure ResponceType:ErrorMsg Response:code.msg];
        }
    }else{
        if(dic!=nil){
            ErrorForServer *server = [ErrorForServer mj_objectWithKeyValues:dic];
            if ([server canBeUsed]) {
                [self fail:failure ResponceType:ServerError Response:server.error.exception];
            }else{
                [self success:success Response:dic];
            }
        }
        else{
            [self fail:failure ResponceType:JsonError Response:nil];
        }
    }
}


/**
 *  返回失败
 *
 *  @param failure failure 回调
 *  @param type    失败类型
 *  @param error   Error
 *
 *  "-1"="系统异常"  "-2"="网络请求超时"  "-3"="服务器返回数据异常"
 *
 */

- (void)fail:(void (^)(NSString *msg))failure ResponceType:(HttpResponse)type Response:(id)error{
    DDLogInfo(@"失败原因===>\n%@", error=nil?@"NULL":error);
    switch (type) {
        case ServerError:
            failure(@"系统异常");
            break;
        case Timeout:
            failure(@"网络请求超时");
            break;
        case JsonError:
            failure(@"服务器返回数据异常");
            break;
        case ErrorMsg:
            failure(NSLocalizedString(O2S(error), nil));
            break;
        default:
            break;
    }
    
}

/**
 *  网络请求成功
 *
 *  @param success        成功
 *  @param responseObject 成功返回的对象
 */

- (void)success:(void (^)(NSDictionary * msg ))success Response:(NSDictionary*)responseObject{
    success(responseObject);
}
/**
 * 上传图片
 * @param url        上传路径
 * @param parameters 上传参数
 * @param image      需要上传的图片
 * @param name       服务器对应的字段
 * @param fileName   文件名称
 * @param success    成功回调
 * @param failure    失败回调
 */
- (void)uploadFileWithUrlString:(NSString*)url parameters:(id)parameters image:(UIImage *)image name:(NSString *)name fileName:(NSString *)fileName success:(void(^)(NSDictionary *dic))success failure:(void(^)(NSString *msg))failure
{
    NSString * httpUrl =[NSString stringWithFormat:@"%@%@",[self getLocalHost],url];
    DDLogError(@"请求的Url:====>%@\n",httpUrl);
    
    DDLogError(@"请求的参数键值对:====>\n");
    for (NSString* key in [(NSDictionary*)parameters allKeys]) {
        DDLogError(@"%@=%@\n",key,[(NSDictionary*)parameters objectForKey:key]);
    }
    DDLogError(@"请求的方式:POST\n");
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:httpUrl parameters:parameters constructingBodyWithBlock:
     ^(id<AFMultipartFormData>  _Nonnull formData) {
         
         [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 1) name:name fileName:fileName mimeType:@"image/png"];
         
     } progress:^(NSProgress * _Nonnull uploadProgress) {
         [DialogUtil showProgressWithMsg:@"上传中..." andEndProgress:1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount];
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         
         //responseObject 响应体信息(默认已经完成了JSON的解析,是一个OC对象)
         [self checkError:success failure:failure Response:responseObject];
         NSLog(@"上传成功---%@",responseObject);
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [self fail:failure ResponceType:Timeout Response:error];
         NSLog(@"上传失败---%@",error);
     }];
}
@end
